import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

class Message{
    public String from;
    public String to;
    public String message;
}

@WebServlet("/message")
public class Servlet extends HttpServlet {
    //使用list来进行保存消息
    //List<Message> list = new ArrayList<>();
    //doget是从服务器获取数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //告诉浏览器我们的数据是json格式,编码方式为utf8
        resp.setContentType("application/json; charset=utf8");
        ObjectMapper objectMapper = new ObjectMapper();
        //writeValue直接可以把list格式转化为json格式
        //并且把这个字符串写到了响应字符串中
        List<Message> list = load();
        objectMapper.writeValue(resp.getWriter(),list);

    }

    //dopost是向服务器提交数据
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        //读取body的内容然后进行解析,解析成Message对象
        Message message =
                objectMapper.readValue(req.getInputStream(),Message.class);
        //list.add(message);
        save(message);
        //返回一个200的响应,200表示成功
        //这里的状态码也可以省略,因为它默认就是200
        resp.setStatus(200);
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        list.remove(list.size()-1);
        delLast();

    }

    //往数据库里面存消息
    public void save(Message message){
        // JDBC 操作
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            // 1. 建立连接
            connection = DBUtil.getConnection();
            // 2. 构造 SQL 语句
//            String sql = "insert into message values(?, ?, ?)";
            String sql = " insert into message(`from`,`to`,message) values(?, ?, ?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1, message.from);
            statement.setString(2, message.to);
            statement.setString(3, message.message);
            // 3. 执行 sql
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 4. 关闭连接.
            DBUtil.close(connection, statement, null);
        }
    }

    //从数据库取所有消息
//    List<Message> messageList = new ArrayList<>();
    public List<Message> load(){
        //messageList = null;
        List<Message> messageList = new ArrayList<>();
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            // 1. 和数据库建立连接
            connection = DBUtil.getConnection();
            // 2. 构造 SQL
            String sql = "select * from message";
            statement = connection.prepareStatement(sql);
            // 3. 执行 SQL
            resultSet = statement.executeQuery();
            // 4. 遍历结果集合
            while (resultSet.next()) {
                Message message = new Message();
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.message = resultSet.getString("message");
                messageList.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 5. 需要释放资源, 断开连接
            DBUtil.close(connection, statement, resultSet);
        }
        return messageList;
    }
    public void delLast(){
        // JDBC 操作
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            // 1. 建立连接
            connection = DBUtil.getConnection();
            // 2. 构造 SQL 语句
            String sql = "delete from message order by id desc limit 1";
            statement = connection.prepareStatement(sql);
            // 3. 执行 sql
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 4. 关闭连接.
            DBUtil.close(connection, statement, null);
        }
    }
}
